﻿using System.Linq;
using System.Web.DomainServices;
using System.Web.DomainServices.Providers;
using System.Web.Ria;
using SoftSource.Timecard.Web.Data;

namespace SoftSource.Timecard.Web.Services
{
    [EnableClientAccess]
    [RequiresAuthentication]
    [RequiresRole("Administrator")]
    public class UserService : LinqToSqlDomainService<UserDBDataContext>
    {
        public IQueryable<User> GetUsers()
        {
            return this.DataContext.Users;
        }

        public User GetUserByID(int userID)
        {
            return this.DataContext.Users.SingleOrDefault(user => user.UserID == userID);
        }

        public void InsertUser(User user)
        {
            user.UserName = UserService.FormatUsername(user.UserName);

            this.DataContext.Users.InsertOnSubmit(user);
        }

        public void UpdateUser(User currentUser)
        {
            currentUser.UserName = UserService.FormatUsername(currentUser.UserName);

            this.DataContext.Users.Attach(currentUser, this.ChangeSet.GetOriginal(currentUser));
        }

        private static string FormatUsername(string username)
        {
            string text = username;
            string formattedUsername;

            // shaun@sftsrc.com
            // sftsrc\shaun
            // shaun
            if (text.Contains('@'))
            {
                formattedUsername = string.Format("SFTSRC\\{0}", text.Split('@').First());
            }
            else
            {
                formattedUsername = text.Contains('\\') ? text : string.Format("SFTSRC\\{0}", text);
            }

            return formattedUsername;
        }

        public void DeleteUser(User user)
        {
            this.DataContext.Users.Attach(user);
            this.DataContext.Users.DeleteOnSubmit(user);
        }
    }
}


